import React from "react";
import{
    Page,
    Form,
    FormCell,
    CellHeader,
    CellsTitle,
    Label,
    CellBody,
    Input,
    ButtonArea,
    Button,
    Toast,
    TextArea,
    Picker,
    Uploader,
    Gallery,
    GalleryDelete,
} from 'react-weui'
import {NavComponent} from "../../components/navgation/NavComponent";
import {getRecordsByIdAction, newRecordByIdAction, updateRecordByIdAction} from "../../actions/recordAction";
import {uploadAction} from "../../actions/uploadAction";
import {getCategoriesAction} from "../../actions/categoryAction";
import {CONST} from "../../base/constant";

export class EditView extends React.Component{

    constructor(props){
        super(props);

        this.state={
            showToast: false,
            showLoading:false,
            showWarning:false,
            warnText:'',
            picker_show: false,
            gallery: false,
            category:[],
            picker_group:[
                {
                    items :[]
                }
            ],
            pickerItem:{},

            originItem:{},//原始对象，删除用

            id:'',
            categoryId:'',
            title: '',
            description: '',
            brief: '',
            imgAfter: [],
            imgBefore: [],
            descAfter: '',
            descBefore: '',
            viewCount: 10,
            recommendCount: 10,
            tags: '',
            isShow:0
        }
    }

    componentDidMount(){

        const that = this;

        console.log(this.props.match.params.recordId);

        const recordId = this.props.match.params.recordId;

        if(recordId === '0'){

            that.getCategory();

            return;

        }

        getRecordsByIdAction(recordId).then(function (res) {

            if(res.id){

                that.state.originItem = Object.assign({},res);

                res.imgBefore = that.resetImageFormat(res.imgBefore);
                res.imgAfter = that.resetImageFormat(res.imgAfter);

                that.setState({...res});

                that.getCategory();

            }else{

                that.setState({showWarning:true,warnText:'接口错误'});

                setTimeout(function () {

                    that.setState({showWarning:false});

                },3000)

            }

        })

    }

    getCategory(){


        getCategoriesAction().then(res=>{

            res.items.forEach(value => {
                value.label = value.name;
                if(value.id === this.state.categoryId){
                    this.state.pickerItem = value;
                }
            })

            console.log([res.items]);

            this.setState({picker_group:[{items:res.items}]});

        })
    }

    resetImageFormat(str){
        const tempArr = str.split(',');
        const returnArr = [];
        for(let i = 0;i<tempArr.length;i++){
            let tempJson = {};
            tempJson.url = CONST.IMG_DOMAIN + '/' + tempArr[i];
            tempJson.dataurl = tempArr[i];
            returnArr.push(tempJson);
        }
        return returnArr;
    }

    getValue(e,type){
        const kv = {};
        kv[type] = e.target.value;
        this.setState(kv);
    }

    uploadImg(file,type){
        const that = this;
        console.log(file.nativeFile)
        const param = new FormData();
        param.append('photo',file.nativeFile);

        uploadAction(param).then(function (res) {

            const item = that.state[type][that.state[type].length-1];

            item.status = undefined;

            item.dataurl = res.path;

            item.url = CONST.IMG_DOMAIN + '/' + res.path;

            console.log(that.state[type]);

            that.setState({...that.state[type]});

        })
        
    }

    save(){

        const that = this;

        this.setState({showLoading:true});

        let imgAfterArr = [];
        let imgBeforeArr = [];
        this.state.imgBefore.map(function (value) {
            imgBeforeArr.push(value.dataurl)
        });
        this.state.imgAfter.map(function (value) {
            imgAfterArr.push(value.dataurl)
        });
        let param = {
            id:this.state.id,
            categoryId:this.state.pickerItem.id,
            title: this.state.title,
            description: this.state.description,
            brief: this.state.brief,
            imgAfter: imgAfterArr.join(','),
            imgBefore: imgBeforeArr.join(','),
            descAfter: '',
            descBefore: '',
            viewCount: this.state.viewCount,
            recommendCount: this.state.recommendCount,
            tags: this.state.tags,
            isShow:this.state.isShow
        }

        console.log(param);

        if(this.props.match.params.recordId === '0'){
            newRecordByIdAction(param).then(function (res) { that.success();})
        }else{
            updateRecordByIdAction(param).then(function (res) { that.success(); })
        }
    }

    deleteItem(){

        const that = this;

        layer.open({
            content: '你确定要删除？<br>删除之后可以恢复，但需要管理员操作恢复'
            ,btn: ['仍要删除', '不要']
            ,yes: function(index){

                layer.close(index);

                that.state.originItem.isShow = 1;

                console.log(that.state.originItem);

                updateRecordByIdAction(that.state.originItem).then(function (res) { that.success(); })
            }
        });

    }


    success() {

        const that = this;

        that.setState({showLoading:false});

        that.setState({showToast:true});

        setTimeout(function () {
            that.setState({showToast:false});
        },3000)
    }

    renderGallery(){

        if(!this.state.gallery) return false;

        const type = this.state.gallery.type;

        let srcs = this.state[type].map(file=>file.url)

        return (
            <Gallery
                src={srcs}
                show
                defaultIndex={this.state.gallery.id}
                onClick={ e=> {
                    //avoid click background item
                    e.preventDefault();
                    e.stopPropagation();
                    this.setState({gallery: false})
                }}
            >

                <GalleryDelete onClick={ (e, id)=> {
                    const kv = {};
                    kv[type] = this.state[type].filter((e,i)=>i !== id);
                    this.setState({
                        ...kv,
                        gallery: this.state[type].length <= 1
                    })
                }} />

            </Gallery>
        )
    }

    render(){

        return <Page infiniteLoader={false}>


            { this.renderGallery() }

            <NavComponent title={"编辑"} history={this.props.history}/>

            <Form>
                <FormCell>
                    <CellHeader>
                        <Label>标题</Label>
                    </CellHeader>
                    <CellBody>
                        <Input value={this.state.title} onChange={(e)=>{this.getValue.bind(this)(e,'title')}} type="text" placeholder="请输入标题"/>
                    </CellBody>
                </FormCell>
                <FormCell onClick={e=>this.setState({picker_show:true})}>
                    <CellHeader>
                        <Label>类别</Label>
                    </CellHeader>
                    <CellBody>
                        <Label>{this.state.pickerItem.name}</Label>
                    </CellBody>
                </FormCell>
                <FormCell>
                    <CellHeader>
                        <Label>标签</Label>
                    </CellHeader>
                    <CellBody>
                        <Input value={this.state.tags} onChange={(e)=>{this.getValue.bind(this)(e,'tags')}} type="text" placeholder="逗号分割"/>
                    </CellBody>
                </FormCell>
                <FormCell>
                    <CellHeader>
                        <Label>浏览量</Label>
                    </CellHeader>
                    <CellBody>
                        <Input value={this.state.viewCount} onChange={(e)=>{this.getValue.bind(this)(e,'viewCount')}} type="text" placeholder="默认自动生成"/>
                    </CellBody>
                </FormCell>
                <FormCell>
                    <CellHeader>
                        <Label>赞</Label>
                    </CellHeader>
                    <CellBody>
                        <Input value={this.state.recommendCount} onChange={(e)=>{this.getValue.bind(this)(e,'recommendCount')}} type="text" placeholder="默认自动生成"/>
                    </CellBody>
                </FormCell>
            </Form>
            <CellsTitle>简介</CellsTitle>
            <Form>
                <FormCell>
                    <CellBody>
                        <TextArea value={this.state.brief} onChange={(e)=>{this.getValue.bind(this)(e,'brief')}} placeholder="输入简介" rows="3" maxLength={100} />
                    </CellBody>
                </FormCell>
            </Form>
            <CellsTitle>描述</CellsTitle>
            <Form>
                <FormCell>
                    <CellBody>
                        <TextArea value={this.state.description} onChange={(e)=>{this.getValue.bind(this)(e,'description')}} placeholder="输入描述" rows="3" maxLength={600} />
                    </CellBody>
                </FormCell>
            </Form>
            <Form>
                <FormCell>
                    <CellBody>

                        <Uploader
                            title="修复前（第一张提取为封面）"
                            maxCount={6}
                            files={this.state.imgBefore}
                            onError={msg => alert(msg)}
                            capture={null}
                            onChange={(file,e) => {
                                let newFiles = [...this.state.imgBefore, {url:file.data,status: '上传中...'}];
                                this.setState({
                                    imgBefore: newFiles
                                });
                                this.uploadImg(file,'imgBefore');
                            }}
                            onFileClick={
                                (e, file, i) => {
                                    console.log('file click', file, i)
                                    this.setState({
                                        gallery: {
                                            url: file.url,
                                            id: i,
                                            type: 'imgBefore'
                                        }
                                    })
                                }
                            }
                            lang={{
                                maxError: maxCount => `Max ${maxCount} images allow`
                            }}
                        />

                    </CellBody>
                </FormCell>
            </Form>
            <Form>
                <FormCell>
                    <CellBody>

                        <Uploader
                            title="修复后（第一张提取为封面）"
                            maxCount={6}
                            files={this.state.imgAfter}
                            onError={msg => alert(msg)}
                            capture={null}
                            onChange={(file,e) => {
                                console.log(file);
                                let newFiles = [...this.state.imgAfter, {url:file.data,status: '上传中...'}];
                                this.setState({
                                    imgAfter: newFiles
                                });
                                this.uploadImg(file,'imgAfter');
                            }}
                            onFileClick={
                                (e, file, i) => {
                                    console.log('file click', file, i)
                                    this.setState({
                                        gallery: {
                                            url: file.url,
                                            id: i,
                                            type: 'imgAfter'
                                        }
                                    })
                                }
                            }
                            lang={{
                                maxError: maxCount => `Max ${maxCount} images allow`
                            }}
                        />

                    </CellBody>
                </FormCell>
            </Form>
            <ButtonArea>
                <Button onClick={this.save.bind(this)}>
                    提交
                </Button>
                <Button onClick={this.deleteItem.bind(this)}>
                    删除，删除之后可恢复
                </Button>
            </ButtonArea>


            <Picker
                onChange={selected=>{
                    let value = ''
                    selected.forEach( (s, i)=> {
                        value = this.state.picker_group[i]['items'][s];
                    });
                    this.setState({
                        pickerItem: value,
                        picker_show: false
                    })
                }}
                groups={this.state.picker_group}
                show={this.state.picker_show}
                onCancel={e=>this.setState({picker_show: false})}
            />

            <Toast icon="success-no-circle" show={this.state.showToast}>提交成功</Toast>
            <Toast icon="loading" show={this.state.showLoading}>处理中...</Toast>
            <Toast icon="toast" iconSize="small" show={this.state.showWarning}>{this.state.warnText}</Toast>
        </Page>

    }

}